package Hash;

import java.util.Arrays;
import java.util.Objects;

public class HashBuck<K,V>{
    static class Node<K,V>{
        public K key;
        public V val;

        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K,V>[] array=(Node<K,V>[])new Node[10];
    public int usedSize;
    public double load_factor=0.75;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashBuck<?, ?> hashBuck = (HashBuck<?, ?>) o;
        return usedSize == hashBuck.usedSize && Double.compare(hashBuck.load_factor, load_factor) == 0 && Arrays.equals(array, hashBuck.array);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(usedSize, load_factor);
        result = 31 * result + Arrays.hashCode(array);
        return result;
    }

    public void put(K key, V val){
        //如何将引用类型转换为整数？ =》hashCode
        int hash=key.hashCode();
        int index=hash%array.length;
        Node<K,V> cur=array[index];
        while(cur!=null){
            if(key.equals(cur.key)){
                cur.val=val;
                return ;
            }
            cur=cur.next;
        }
        Node<K,V> node=new Node(key,val);
        node.next=array[index];
        array[index]=node;
        usedSize++;
        //检查是否需要扩容

    }

    public V get(K key){
        int hash=key.hashCode();
        int index=hash%array.length;
        Node<K,V> cur=array[index];
        while(cur!=null){
            if(cur.key.equals(key)){
                return cur.val;
            }
            cur=cur.next;
        }
        return null;
    }
}
